package com.snoweagler.JmsSend;


import com.snoweagler.VO.PageVO;
import com.snoweagler.VO.ResponseVO;
import com.snoweagler.params.UserParams;
import com.snoweagler.pojo.Role;
import com.snoweagler.pojo.User;
import com.snoweagler.service.UserService;
import com.snoweagler.util.PoiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;
    @RequestMapping("/list")
    public PageVO<User> getUserList(UserParams params){
        return service.getUserList(params);
    }

    @RequestMapping("/edit")
    public ResponseVO edit(User user){
        try {
            service.edit(user);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseVO.error();
        }
        return ResponseVO.ok();
    }
    @RequestMapping("/getOptions")
    public List<Role> getOptions(){
        return service.getOptions();
    }
    @GetMapping("/outExecl")
    public ResponseEntity<byte[]> getOutExecl() {

        try{
        HttpStatus status = HttpStatus.OK;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息.xls", "utf-8"));

        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        List<User> data = service.findAllUsers();
        PoiUtil.exportExecl(bao, Arrays.asList("ID", "用户名", "邮箱", "手机号", "角色"), Arrays.asList("id", "name", "email", "mobile", "remark"), data);

        byte[] body = bao.toByteArray();//把输出流的数据转成字节数组
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, status);
        return responseEntity;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
    @RequestMapping("/inputForm")
    public Object inputForm(){

        PoiUtil.inputFrom("D://TSBrowserDownloads/userinfo.xls");
        return 0;
    }
}
